package com.myproject.http;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * @Description: //TODO  简单的HTTP服务器， 其实就是接受HTTP请求，并解析请求，
 * @Author: sunfch
 * @Date: 2019/1/3 16:35
 * @Param:
 * @Return:
 */
public class NioHttpServer {

    public static void main(String[] args) throws Exception{


        ServerSocketChannel ss = ServerSocketChannel.open();  //服务端开启监听：接受客户端
        ss.bind(new InetSocketAddress(9960));
        ss.configureBlocking(false); //重点  OS  NONBLOCKING!!!  //只让接受客户端  不阻塞

        while (true){

            //接受客户端的连接
             SocketChannel client = ss.accept(); //不会阻塞？  -1 NULL
            if (client!=null){
                System.out.println(client+" connect");
                client.configureBlocking(false);
                ClientHandler clientHandler = new ClientHandler(client);
                clientHandler.start();
            }

        }
    }

    public static class ClientHandler extends Thread{

        private SocketChannel socket;

        public ClientHandler(SocketChannel socket){
            this.socket = socket;
        }

        @Override
        public void run() {


            //弊端 1.报文不能太大  2.报文不能多次发送
            try {
                ByteBuffer buffer = ByteBuffer.allocate(2048);  //可以在堆里   堆外
                String message;
                while (true){
                    int num = socket.read(buffer);
                    System.out.println("num:"+num);
                    if (num>0){
                        buffer.flip();
                        byte[] bytes = new byte[buffer.limit()];
                        buffer.get(bytes);
                        message = new String(bytes);
                        System.out.println(message);
                        break;
                    } else if (num==-1){
                        System.out.println(socket+" close");

                        break;
                    }
                }

                //解析报文

                ByteBuffer out = ByteBuffer.allocate(1024);
                StringBuilder sb = new StringBuilder();
                sb.append("HTTP/1.1 200 OK\r\n");
                sb.append("Content-type:text/html\r\n");
                sb.append("\r\n");
                sb.append("<h1>successful</h1>");
                out.put(sb.toString().getBytes());
                out.flip();
                socket.write(out);

                socket.close();

            } catch (Exception e){
                e.printStackTrace();
            }


        }
    }
}